package com.flick.base.ctrl;

import com.flick.base.service.QueryServ;
import com.flick.common.Filters;
import com.flick.common.ObjectToResult;
import com.flick.common.PageParam;
import com.flick.common.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

/**
 * Created by flick on 2017/4/23.
 */
@EnableAutoConfiguration
@CrossOrigin
public class QueryCtrl<T,Serv extends QueryServ>{

    @Autowired
    Serv serv;

    /**
     * 查看所有商品类型列表
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Object list() throws Exception{
        Filters filters = new Filters();
        return ObjectToResult.getResult(serv.list(filters));
    }

     /**
     * 查看商品分类列表（带分页+单项查询）
     * @param rows 页码
     * @param page 每页大小
     * @param sidx 排序字段
     * @param sord 排序类型
     * @param searchField 查询值
     * @param searchString 查询字符串
     * @param searchOper 查询连接词
     * @return
     */
    @RequestMapping(params = {"page","rows"},method = RequestMethod.GET)
    public Object page(@RequestParam Integer page,@RequestParam Integer rows,
                       @RequestParam(required = false) String sidx,@RequestParam(required = false) String sord,
                       @RequestParam(required = false) String searchField,@RequestParam(required = false) String searchString,
                       @RequestParam(required = false) String searchOper) throws Exception{
        PageParam pageParam = new PageParam();
        pageParam.setPageNum(page);
        pageParam.setPageSize(rows);
        pageParam.setSidx(sidx);
        pageParam.setSord(sord);
        if(searchField != null &&searchString != null &&searchOper != null) {
            Filters filters = new Filters();
            filters.setGroupOp("and");
            ArrayList<Rule> rules = new ArrayList<>();
            Rule rule = new Rule();
            rule.setField(searchField);
            rule.setData(searchString);
            rule.setOp(searchOper);
            rules.add(rule);
            filters.setRules(rules);
            pageParam.setFilters(filters);
        }
        return ObjectToResult.getResult(serv.page(pageParam));
    }

    /**
     * 根据ID查看商品分类
     * @param id 商品ID
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Object get (@PathVariable String id) throws Exception{
        return ObjectToResult.getResult(serv.get(id));
    }
}
